package com.grq.mis.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.grq.mis.dao.ItemDao;
import com.grq.mis.dao.LoginRecordDao;
import com.grq.mis.dao.OrderDao;
import com.grq.mis.dao.UserDao;
import com.grq.mis.entity.Department;
import com.grq.mis.entity.Notice;
import com.grq.mis.entity.User;
import com.grq.mis.exception.BusinessException;
import com.grq.mis.exception.ResultData;
import com.grq.mis.exception.ResultEnum;
import com.grq.mis.model.sys.Me;
import com.grq.mis.model.view.Menu;
import com.grq.mis.satoken.SaTokenRealm;
import com.grq.mis.service.DepartmentService;
import com.grq.mis.service.NoticeService;
import com.grq.mis.service.UserService;
import com.grq.mis.validate.UserValidate;
import org.beetl.core.GroupTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private SaTokenRealm saTokenRealm;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private GroupTemplate groupTemplate;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private LoginRecordDao loginRecordDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ItemDao itemDao;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;

    /**
     * 登录页面
     * @return
     */
    @GetMapping("/login")
    public String getLogin() {
        if (!StpUtil.isLogin()) {
            return "login.html";
        }
        return "redirect:/";
    }

    /**
     * 验证码
     * @param request
     * @param response
     */
    @GetMapping("/validate")
    public void validate(HttpServletRequest request, HttpServletResponse response) {

        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);

        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40, 4, 100);
        //LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40);
        lineCaptcha.setGenerator(randomGenerator);

        // 重新生成code
        lineCaptcha.createCode();

        // 验证码保存到session中
        request.getSession().setAttribute("validateCode", lineCaptcha.getCode());

        try {
            lineCaptcha.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param validateCode
     * @param request
     * @param model
     * @return
     */
    @PostMapping("/login")
    public String postLogin(String username, String password, String validateCode, HttpServletRequest request, Model model) {

        String code = (String) request.getSession().getAttribute("validateCode");
        if (Validator.isEmpty(code)) {
            return "redirect:/login";
        }
        if (!code.equalsIgnoreCase(validateCode)) {
            model.addAttribute("result", ResultEnum.VALIDATE_CODE_ERROR);
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            return "login.html";
        }

        try {
            saTokenRealm.login(username, password);
        } catch (BusinessException e) {
            model.addAttribute("result", new ResultData(e.getCode(), e.getMsg()));
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            return "login.html";
        }

        return "redirect:/";
    }

    /**
     * 主页
     * @param model
     * @return
     */
    @GetMapping("/")
    public String index(Model model) {

        SaSession ss = StpUtil.getSession();

        // 菜单 只放在model中
        List<Menu> menus = (List<Menu>) ss.get("menus");
        if (menus == null) {
            menus = new ArrayList<>();
        }
        model.addAttribute("menus", menus);

        // me 只放在全局中
        Me me = (Me) ss.get("me");
        Map<String, Object> shares = groupTemplate.getSharedVars();
        shares.put("me", me);
        // model.addAttribute("me", me);

        // notice
        Notice notice = noticeService.getLast();
        model.addAttribute("notice",notice);
        if (notice == null){
            model.addAttribute("isTip",0);
        }else{
            if (notice.getIsTip() == true){
                model.addAttribute("isTip",1);
            }else{
                model.addAttribute("isTip",0);
            }
        }

        return "index.html";
    }

    /**
     * 欢迎页
     * @return
     */
    @GetMapping("/welcome")
    public String welcome(Model model) {

        long allMoney = orderDao.allMoney();
        model.addAttribute("allMoney",allMoney);

        long allVisit = loginRecordDao.allVisit();
        model.addAttribute("allVisit",allVisit);

        long allUser = userDao.allUser();
        model.addAttribute("allUser",allUser);

        long allItem = itemDao.allItem();
        model.addAttribute("allItem",allItem);

        String today = DateUtil.today();

        long todayMoney = orderDao.todayMoney(today);
        model.addAttribute("todayMoney",todayMoney);

        long todayVisit = loginRecordDao.todayVisit(today);
        model.addAttribute("todayVisit",todayVisit);

        long todayUser = userDao.todayUser(today);
        model.addAttribute("todayUser",todayUser);

        long todayItem = itemDao.todayItem(today);
        model.addAttribute("todayItem",todayItem);

        return "welcome.html";
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping("/logout")
    public String logout() {
        StpUtil.logout();
        return "redirect:/";
    }

    @GetMapping("/registerForm")
    public String registerForm(Model model){

        List<Department> departments = departmentService.createLambdaQuery().andEq(Department::getIsDisable,false).select();
        model.addAttribute("departments",departments);

        return "register.html";
    }

    @PostMapping("/register")
    public String register(RedirectAttributes attr, User user){

        UserValidate.register(user);

        userService.register(user);

        return pageSuccess(attr, "/login", ResultEnum.SUCCESS, "注册成功");
    }

    @GetMapping("/updateMyInfoForm")
    public String updateMyInfoForm(Model model){

        Me me = me();
        User user = userService.single(me.getId());
        if (user == null){
            throw new BusinessException(ResultEnum.ERROR,"个人信息不存在");
        }

        model.addAttribute("user",user);

        return "update.html";
    }

    @PostMapping("/updateMyInfo")
    public String updateMyInfo(Model model, User user){

        UserValidate.updateMyInfo(user);

        Me me = me();
        userService.updateMyInfo(user,me);

        return frameSuccess(model, ResultEnum.SUCCESS, "修改资料成功");
    }

}
